#coding:utf8
#author:CMGS

import urllib2
import hashlib

def openFile(filePath):
    content = open(filePath, 'rb').read()
    
    size = len(content)

    mysha1 = hashlib.sha1()
    mysha1.update(content)
    mySha1_Digest = mysha1.hexdigest()
    sha1 = mySha1_Digest.upper()
    return content, str(size), sha1

def makeFileList(source):
    retData = {}
    for v in source:
        retData[v.get('name')] = v.get('fileId')
    return retData

def creatxml(params):
    xml = '<?xml version="1.0" encoding="utf-8" ?><xLive>'
    for key, value in params.iteritems():
        xml = xml + '<%s>%s</%s>' % (str(key), str(value), str(key))
    xml = xml + '</xLive>'
    return xml

def post_multipart(url, fields, files, cont_type):
    content_type, body = encode_multipart_formdata(fields, files, cont_type)
    req = urllib2.Request(url, body, {'content-type':content_type, 'content-length':str(len(body))})
    return urllib2.urlopen(req).read()

def encode_multipart_formdata(fields, files, cont_type):
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        #L.append('Content-Type: %s' % 'application/octet-stream')
        L.append('Content-Type: %s' % cont_type)
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')

    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
